/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.test;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import org.bson.types.ObjectId;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@SpringBootTest
public class MongoDBTest {

    @Autowired
    private MongoClient mongoClient; // 连接117

    @Autowired
    private MongoTemplate mongoTemplate; // 连接117

    @Autowired
    @Qualifier("secondaryMongoTemplate")
    private MongoTemplate secondaryMongoTemplate; // 连接118


    @Autowired
    private GridFsTemplate gridFsTemplate; // 连接118

    @Test
    void test() {
        // 使用主MongoClient (117)
        mongoClient.getDatabase("comac_db").createCollection("hxloongs5");
        mongoTemplate.createCollection("hxloongs6");
        // 使用GridFsTemplate (118)
        // 这里可以添加GridFs操作测试
        System.out.println("测试多数据源配置成功");

        secondaryMongoTemplate.createCollection("hxloongs7");
    }

    @Test
    void testGridFsConnection() {
        try {
            // 尝试执行一个简单的GridFs操作来测试连接
            long fileCount = gridFsTemplate.find(new org.springframework.data.mongodb.core.query.Query()).spliterator().getExactSizeIfKnown();
            System.out.println("GridFsTemplate 连接成功，文件数量: " + fileCount);

            // 或者尝试存储一个测试文件
            String testContent = "测试连接的文件内容";
            InputStream inputStream = new ByteArrayInputStream(testContent.getBytes(StandardCharsets.UTF_8));
            ObjectId fileId = gridFsTemplate.store(inputStream, "test_connection.txt", "text/plain");
            System.out.println("GridFsTemplate 测试文件存储成功，文件ID: " + fileId);

            // 清理测试文件
            gridFsTemplate.delete(org.springframework.data.mongodb.core.query.Query.query(
                org.springframework.data.mongodb.core.query.Criteria.where("_id").is(fileId)
            ));

        } catch (Exception e) {
            System.out.println("GridFsTemplate 连接测试失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
